package com.weather.pm.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.weather.pm.BaseActivity;
import com.weather.pm.Constants;
import com.weather.pm.R;
import com.weather.pm.WeatherApplication;
import com.weather.pm.beans.Weather;
import com.weather.pm.utils.IconUtils;
import com.weather.pm.utils.VolleyTool;
import com.weather.pm.utils.WXShareUtil;
import com.weather.pm.utils.WeiBoShareUtil;
import com.weather.pm.utils.VolleyTool.HTTPListener;

public class WeatherDetailActivity extends BaseActivity implements OnClickListener,IWeiboHandler.Response,HTTPListener{
	private ImageButton share;
	private PopupWindow popupWindow;
	public static IWeiboShareAPI  mWeiboShareAPI = null;
	private ImageButton goBack;
	private Weather weather = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setFullScreen();
		setContentView(R.layout.weather_detail_activity);
		if(this.getIntent().getExtras() != null && this.getIntent().getExtras().containsKey("id")){
			String id = this.getIntent().getExtras().getString("id");
			Map<String,String> params = new HashMap<String,String>();
			params.put("idList", id+"");
			VolleyTool.get(Constants.GET_WEATHER_LIST, params, this,
					Constants.GETWEATHERLIST);
		}else{
			weather = (Weather)this.getIntent().getBundleExtra("weather").getSerializable("weather");
			initView();
		}
		// 注册新浪
		WeiBoShareUtil.registerToWX(this);
		mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, WeiBoShareUtil.WEIBO_KEY);
		mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
		WXShareUtil.registerToWX(this);
	}

	private void initView(){
		goBack = (ImageButton)this.findViewById(R.id.imb_back);
		goBack.setOnClickListener(this);
		share = (ImageButton)findViewById(R.id.imb_share);
		share.setOnClickListener(this);
		findViewById(R.id.markIcon).setOnClickListener(this);
		RelativeLayout layout = (RelativeLayout)this.findViewById(R.id.detailLayout);
		Calendar c = Calendar.getInstance();  
		int hour = c.get(Calendar.HOUR_OF_DAY);
		if(hour > 6 && hour < 18){
			layout.setBackgroundResource(R.drawable.bg_day);
		}else{
			layout.setBackgroundResource(R.drawable.bg_night);
		}
		//layout.setBackgroundResource(R.drawable.bg_night);
		//layout.setBackgroundResource(R.drawable.bg_night);
	//	Weather weather = (Weather)this.getIntent().getBundleExtra("weather").getSerializable("weather");
		// top的几天天�?
		((TextView)this.findViewById(R.id.topUptext1)).setText(/*weather.datas.get(0).date*/"今天");
		((TextView)this.findViewById(R.id.topDwonText1)).setText(weather.datas.get(0).temperature);
		((ImageView)layout.findViewById(R.id.topUpImage1)).setBackgroundResource
		(IconUtils.getIconId(IconUtils.getIconName(weather.datas.get(0).dayPictureUrl))[0]);
		
		((TextView)this.findViewById(R.id.topUptext2)).setText(weather.datas.get(1).date);
		((TextView)this.findViewById(R.id.topDwonText2)).setText(weather.datas.get(1).temperature);
		((ImageView)layout.findViewById(R.id.topUpImage2)).setBackgroundResource
		(IconUtils.getIconId(IconUtils.getIconName(weather.datas.get(1).dayPictureUrl))[0]);
		
		((TextView)this.findViewById(R.id.topUptext3)).setText(weather.datas.get(2).date);
		((TextView)this.findViewById(R.id.topDwonText3)).setText(weather.datas.get(2).temperature);
		((ImageView)layout.findViewById(R.id.topUpImage3)).setBackgroundResource
		(IconUtils.getIconId(IconUtils.getIconName(weather.datas.get(2).dayPictureUrl))[0]);
		
		((TextView)this.findViewById(R.id.topUptext4)).setText(weather.datas.get(3).date);
		((TextView)this.findViewById(R.id.topDwonText4)).setText(weather.datas.get(3).temperature);
		((ImageView)layout.findViewById(R.id.topUpImage4)).setBackgroundResource
		(IconUtils.getIconId(IconUtils.getIconName(weather.datas.get(3).dayPictureUrl))[0]);
		// 中部天气 农历信息
		
		((ImageView)layout.findViewById(R.id.icon_weather_now)).setBackgroundResource
		(IconUtils.getIconId(IconUtils.getIconName(weather.datas.get(0).dayPictureUrl))[1]);
		((TextView)this.findViewById(R.id.date)).setText("©国家环境保护部\n"+weather.datas.get(0).date+"\n农历 "+weather.lunar);
		((TextView)this.findViewById(R.id.temperature)).setText(weather.datas.get(0).temperature);
		((TextView)this.findViewById(R.id.temperatureWord)).setText(weather.datas.get(0).weather);
		((TextView)this.findViewById(R.id.pmText)).setText(weather.pm25Mode.aqi);
		
		((TextView) this.findViewById(R.id.limitText)).setText(weather.trafficControl);
		((TextView) this.findViewById(R.id.windDirection)).setText(weather.datas.get(0).wind);
		((TextView) this.findViewById(R.id.humidity)).setText(weather.humidity);
		ImageView iconPm = (ImageView)this.findViewById(R.id.iconPm);
		int pm25 = Integer.parseInt(weather.pm25Mode.pm25);
		if(pm25 < 50){
			iconPm.setBackgroundResource(R.drawable.air_level_4);
		}else if(pm25 >50 && pm25 < 100){
			iconPm.setBackgroundResource(R.drawable.air_level_2);
		}else if(pm25 > 100 && pm25 < 150){
			iconPm.setBackgroundResource(R.drawable.air_level_1);
		}else if(pm25 > 150 && pm25 < 200){
			iconPm.setBackgroundResource(R.drawable.air_level_6);
		}else if(pm25 > 200 && pm25 < 250){
			iconPm.setBackgroundResource(R.drawable.air_level_7);
		}else if(pm25 > 250 && pm25 <300){
			iconPm.setBackgroundResource(R.drawable.air_level_1);
		}else{
			iconPm.setBackgroundResource(R.drawable.air_level_3);
		}
		// 生活小贴�?

		((TextView)this.findViewById(R.id.tv_title)).setText(weather.cityName);
		((TextView)this.findViewById(R.id.lifeUptext1)).setText(weather.indexs.get(1).zs);
		//((TextView)this.findViewById(R.id.lifeDowntext1)).setText(weather.indexs.get(1).title);

		((TextView)this.findViewById(R.id.lifeUptext2)).setText(weather.indexs.get(3).zs);
		//((TextView)this.findViewById(R.id.lifeDowntext2)).setText(weather.indexs.get(3).title);

		((TextView)this.findViewById(R.id.lifeUptext3)).setText(weather.indexs.get(2).zs);
		//((TextView)this.findViewById(R.id.lifeDowntext3)).setText(weather.indexs.get(2).title);

		((TextView)this.findViewById(R.id.lifeUptext4)).setText(weather.indexs.get(0).zs);
		//((TextView)this.findViewById(R.id.lifeDowntext4)).setText(weather.indexs.get(0).title);
		((TextView)this.findViewById(R.id.lifeDowntext4)).setText(weather.indexs.get(0).title);
		// 污染�?
		((TextView)this.findViewById(R.id.pm25Value)).setText(weather.pm25Mode.pm25);
		((TextView)this.findViewById(R.id.pm10Value)).setText(weather.pm25Mode.pm10);
		((TextView)this.findViewById(R.id.so2)).setText(weather.pm25Mode.so2);
		((TextView)this.findViewById(R.id.o3Value)).setText(weather.pm25Mode.o3);
		((TextView)this.findViewById(R.id.no2Value)).setText(weather.pm25Mode.no2);
		((TextView)this.findViewById(R.id.coValue)).setText(weather.pm25Mode.co);
	}

	/**
	 * @see {@link Activity#onNewIntent}
	 */	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		// 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函�?
		// 来接收微博客户端返回的数据；执行成功，返�?true，并调用
		// {@link IWeiboHandler.Response#onResponse}；失败返�?false，不调用上述回调
		mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imb_back:
			finish();
			break;
		case R.id.imb_share:
			createPopup();
			break;
		case R.id.share_weibo:
			if(weather == null) return;
			//int[] pics = IconUtils.getIconId(IconUtils.getIconName(weather.datas.get(0).dayPictureUrl));
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon_108);
			WeiBoShareUtil.sendMessage(weather.cityName+" 今天" +weather.datas.get(0).weather +","+weather.datas.get(0).temperature+","+weather.datas.get(0).wind+";[明天]"
					+weather.datas.get(1).weather +","+weather.datas.get(1).temperature+","+weather.datas.get(1).wind, bmp, "http://www.its-one.com.cn/");
			popupWindow.dismiss();
			// 分享网页到新浪微博的时�? 如果你的url地址不是以http�?��的话 ，是不会显示“网页链接�?的；
			//WeiBoShareUtil.sendMessage("乐艺�?, imageUrl, "http://www.openart.cn/artwork-"+artWorkId,artName);
			break;
		case R.id.share_weixin:
			if(weather == null) return;
			shareToWeixin(true,weather.cityName+" "+weather.datas.get(0).weather +" "+weather.datas.get(0).temperature,
					weather.cityName+" 今天 "+weather.datas.get(0).weather +","+weather.datas.get(0).temperature+","+weather.datas.get(0).wind+";[明天] "
			+weather.datas.get(1).weather +","+weather.datas.get(1).temperature+","+weather.datas.get(1).wind,
			"http://www.its-one.com.cn/",
			weather.datas.get(0).dayPictureUrl);
			popupWindow.dismiss();
			break;
		case R.id.share_weixinpengyou:
			popupWindow.dismiss();
			shareToWeixin(false,weather.cityName+" "+weather.datas.get(0).weather +" "+weather.datas.get(0).temperature,
					weather.cityName+" 今天  "+weather.datas.get(0).weather +","+weather.datas.get(0).temperature+","+weather.datas.get(0).wind+";【明天]"+
			weather.datas.get(1).weather +","+weather.datas.get(1).temperature+","+weather.datas.get(1).wind,"http://www.its-one.com.cn/",
			weather.datas.get(0).dayPictureUrl);
			break;
		case R.id.markIcon:
			creatDialog();
			break;
		default:
			break;
		}

	}

	private void creatDialog() {
		Dialog dialog = new Dialog(this,R.style.MyDialog);
		dialog.setContentView(R.layout.disabuse_dialog);
		dialog.show();

	}

	private void shareToWeixin(boolean bol,String title,String content,String url,String imageUrl){
		//String thumb_url1 = new StringBuilder(12).append("#W").append(0).append("#H").append(0).append("").toString();
		//int[] pics = IconUtils.getIconId(IconUtils.getIconName(imageUrl));
		Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon_108);
		WXShareUtil.shareWebPage(url,bmp, title, content, bol);
	}



	private void createPopup() {

		View contentView = LayoutInflater.from(this).inflate(R.layout.share_dialog, null);
		contentView.findViewById(R.id.share_weibo).setOnClickListener(this);
		contentView.findViewById(R.id.share_weixin).setOnClickListener(this);
		contentView.findViewById(R.id.share_weixinpengyou).setOnClickListener(this);

		popupWindow =
				new PopupWindow(contentView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		// 使其聚集  
		popupWindow.setFocusable(true);  
		// 设置允许在外点击消失  
		popupWindow.setOutsideTouchable(true);  

		// 这个是为了点击�?返回Back”也能使其消失，并且并不会影响你的背�? 
		popupWindow.setBackgroundDrawable(new BitmapDrawable());  
		popupWindow.showAtLocation(share, Gravity.CENTER, 0, 0);



	}

	@Override
	public void onResponse(BaseResponse arg0) {
		
	}

	ArrayList<Weather> weathers = null;
	@Override
	public void onResponse(String response, int requestCode) {

		try {

			JSONObject json = new JSONObject(response);
			int status = json.getInt("Status");
			String message = json.getString("Message");

			if (status == 0) {
				weathers = new ArrayList<Weather>();
				// 解析�?��的城市天气信�?
				JSONArray infos = new JSONArray(json.getString("Result"));
				JSONObject obj = null;
				for (int i = 0; i < infos.length(); i++) {
					Weather weather = new Weather();
					Weather.WeatherData data = null;
					Weather.Index index = null;
					obj = infos.getJSONObject(i);
					// 初始化weather实体
					weather.datas = new ArrayList<Weather.WeatherData>();
					weather.indexs = new ArrayList<Weather.Index>();

					// 解析datas数据
					JSONObject cityWeather = obj.getJSONObject("CityWeather");
					JSONArray results = cityWeather.getJSONArray("results");
					JSONObject cityRe = results.getJSONObject(0);
					// 初始化weather的城市数据和pm2.5�?
					weather.cityName = cityRe.getString("currentCity");
					weather.pm25 = cityRe.getString("pm25");
					weather.humidity = cityRe.getString("humidity");

					// 初始化weather中datas数据
					JSONArray dataA = cityRe.getJSONArray("weather_data");
					for (int j = 0; j < dataA.length(); j++) {
						data = weather.new WeatherData();
						JSONObject doo = dataA.getJSONObject(j);
						data.date = doo.getString("date");
						data.weather = doo.getString("weather");
						data.dayPictureUrl = doo.getString("dayPictureUrl");
						data.wind = doo.getString("wind");
						data.temperature = doo.getString("temperature");
						weather.datas.add(data);
					}

					// 初始化weather中index数据
					JSONArray indexA = cityRe.getJSONArray("index");
					for (int j = 0; j < indexA.length(); j++) {
						index = weather.new Index();
						JSONObject io = indexA.getJSONObject(j);
						index.title = io.getString("title");
						index.zs = io.getString("zs");
						index.tipt = io.getString("tipt");
						index.des = io.getString("des");
						weather.indexs.add(index);
					}

					weather.trafficControl = obj.getString("trafficControl");
					weather.lunar = obj.getString("lunar");

					// 获取Pm2.5Model数�?
					Weather.Pm25Model pm25 = weather.new Pm25Model();
					JSONObject pmModel = obj.getJSONObject("Pm25Model");
					pm25.pm25 = pmModel.getString("Pm25");
					pm25.pm10 = pmModel.getString("Pm10");
					pm25.so2 = pmModel.getString("So2");
					pm25.o3 = pmModel.getString("O3");
					pm25.no2 = pmModel.getString("No2");
					pm25.co = pmModel.getString("Co");
					pm25.quality = pmModel.getString("quality");
					pm25.level = pmModel.getString("level");
					pm25.datetime = pmModel.getString("datetime");
					pm25.positionName = pmModel.getString("position_name");
					pm25.aqi = pmModel.getString("aqi");
					weather.pm25Mode = pm25;
					/*if (myCitys.size() != 0) {
						for (City city : myCitys) {
							if (city.name.equals(weather.cityName)) {
								city.weather = weather;
							}
						}
					}*/
					weathers.add(weather);
				}
				if(weathers.size() > 0){
					weather = weathers.get(0);
					initView();
				}else{
					Toast.makeText(WeatherApplication.getInstance().getApplicationContext(), "该城市暂不支持查询", Toast.LENGTH_LONG).show();
				}
				/*if(myCitys.size()!=0){
					WeatherApplication.getInstance().myCities = myCitys;
				}else {
					City  city = new City();
					city.id =7;
					city.name = "北京";
					city.weather = weathers.get(0);
					WeatherApplication.getInstance().myCities.add(city);
				}*/
				// 初始化ViewPager中的各项子View
				/*layouts = new ArrayList<View>();
				for (int j = 0; j < weathers.size(); j++) {
					View layout = createView(weathers.get(j));
					layouts.add(layout);
				}
				// 动�?设置 2个部分的高度为整屏幕
				mCityName.setText(weathers.get(0).cityName);
				mIndicator.setCount(layouts.size());
				pagerAdapter = new HomePagerAdapter();
				pagerAdapter.setData(layouts);
				mViewPager.setAdapter(pagerAdapter);
				isfirst = false;*/
			} else {
					Toast.makeText(WeatherApplication.getInstance().getApplicationContext(), message, Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
